// 全局变量
let availableOptions = null;
let currentSystemInfo = null;
let downloadProgressHandler = null;
let isDownloading = false;

// DOM 元素
const osSelect = document.getElementById('os-select');
const archSelect = document.getElementById('arch-select');
const versionSelect = document.getElementById('version-select');
const vendorSelect = document.getElementById('vendor-select');
const downloadBtn = document.getElementById('download-btn');
const cancelBtn = document.getElementById('cancel-btn');
const downloadSection = document.getElementById('download-section');
const progressFill = document.getElementById('progress-fill');
const progressText = document.getElementById('progress-text');
const downloadDetails = document.getElementById('download-details');
const downloadStatus = document.getElementById('download-status');
const resultSection = document.getElementById('result-section');
const resultPath = document.getElementById('result-path');

// 初始化应用
async function initApp() {
  try {
    // 获取系统信息
    currentSystemInfo = await window.electronAPI.getSystemInfo();
    console.log('当前系统信息:', currentSystemInfo);

    // 获取可用选项
    availableOptions = await window.electronAPI.getAvailableOptions();
    console.log('可用选项:', availableOptions);

    // 初始化供应商选择框
    populateVendorSelect();

    // 设置默认供应商（优先选择 Azul）
    const preferredVendors = ['Azul', 'Microsoft', 'Oracle', 'Eclipse', 'Amazon'];
    let selectedVendor = availableOptions.vendors[0];

    for (const vendor of preferredVendors) {
      if (availableOptions.vendors.includes(vendor)) {
        selectedVendor = vendor;
        break;
      }
    }
    vendorSelect.value = selectedVendor;

    // 触发操作系统更新
    await updateOSOptions();

    // 启用下载按钮
    downloadBtn.disabled = false;
    downloadBtn.textContent = '开始下载';

  } catch (error) {
    console.error('初始化失败:', error);
    showError('应用初始化失败，请检查配置文件。');
  }
}

// 填充供应商选择框
function populateVendorSelect() {
  if (!availableOptions) return;

  vendorSelect.innerHTML = '';

  availableOptions.vendors.forEach(vendor => {
    const option = document.createElement('option');
    option.value = vendor;
    option.textContent = vendor;
    vendorSelect.appendChild(option);
  });
}

// 更新操作系统选项（基于选中的供应商）
async function updateOSOptions() {
  const selectedVendor = vendorSelect.value;
  if (!selectedVendor) return;

  try {
    const operatingSystems = await window.electronAPI.getOSForVendor(selectedVendor);

    osSelect.innerHTML = '';

    if (operatingSystems.length === 0) {
      const option = document.createElement('option');
      option.value = '';
      option.textContent = '无可用操作系统';
      osSelect.appendChild(option);
      return;
    }

    operatingSystems.forEach(os => {
      const option = document.createElement('option');
      option.value = os;
      option.textContent = os;
      osSelect.appendChild(option);
    });

    // 设置默认操作系统
    if (currentSystemInfo.os && operatingSystems.includes(currentSystemInfo.os)) {
      osSelect.value = currentSystemInfo.os;
    } else {
      osSelect.value = operatingSystems[0];
    }

    // 触发架构更新
    await updateArchitectureOptions();

  } catch (error) {
    console.error('更新操作系统选项失败:', error);
  }
}

// 更新架构选项（基于选中的供应商和操作系统）
async function updateArchitectureOptions() {
  const selectedVendor = vendorSelect.value;
  const selectedOS = osSelect.value;
  if (!selectedVendor || !selectedOS) return;

  try {
    const architectures = await window.electronAPI.getArchitecturesForVendorOS(selectedVendor, selectedOS);

    archSelect.innerHTML = '';

    if (architectures.length === 0) {
      const option = document.createElement('option');
      option.value = '';
      option.textContent = '无可用架构';
      archSelect.appendChild(option);
      return;
    }

    architectures.forEach(arch => {
      const option = document.createElement('option');
      option.value = arch;
      option.textContent = arch;
      archSelect.appendChild(option);
    });

    // 设置默认架构
    if (currentSystemInfo.arch && architectures.includes(currentSystemInfo.arch)) {
      archSelect.value = currentSystemInfo.arch;
    } else {
      archSelect.value = architectures[0];
    }

    // 触发版本更新
    await updateVersionOptions();

  } catch (error) {
    console.error('更新架构选项失败:', error);
  }
}

// 更新版本选项（基于选中的供应商、操作系统和架构）
async function updateVersionOptions() {
  const selectedVendor = vendorSelect.value;
  const selectedOS = osSelect.value;
  const selectedArch = archSelect.value;
  if (!selectedVendor || !selectedOS || !selectedArch) return;

  try {
    const versions = await window.electronAPI.getVersionsForOSArchVendor(selectedOS, selectedArch, selectedVendor);

    versionSelect.innerHTML = '';

    if (versions.length === 0) {
      const option = document.createElement('option');
      option.value = '';
      option.textContent = '无可用版本';
      versionSelect.appendChild(option);
      return;
    }

    versions.forEach(version => {
      const option = document.createElement('option');
      option.value = version;
      option.textContent = `JDK ${version}`;
      versionSelect.appendChild(option);
    });

    // 设置默认版本（优先选择稳定的 LTS 版本）
    const preferredVersions = ['21.0.8', '21', '17.0.16', '17', '11.0.20', '11'];
    let selectedVersion = versions[0];

    for (const version of preferredVersions) {
      if (versions.includes(version)) {
        selectedVersion = version;
        break;
      }
    }
    versionSelect.value = selectedVersion;

  } catch (error) {
    console.error('更新版本选项失败:', error);
  }
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 更新下载进度
function updateDownloadProgress(progressData) {
  const { progress, downloaded, total, fileName } = progressData;

  // 更新进度条
  progressFill.style.width = `${progress}%`;
  progressText.textContent = `${progress}%`;

  // 更新详细信息
  const downloadedMB = formatFileSize(downloaded);
  const totalMB = formatFileSize(total);
  downloadDetails.textContent = `已下载: ${downloadedMB} / 总大小: ${totalMB}`;

  // 更新状态信息
  downloadStatus.innerHTML = `<p>正在下载: ${fileName}</p>`;
}

// 显示错误信息
function showError(message) {
  downloadStatus.innerHTML = `<p class="error">${message}</p>`;
}

// 显示成功信息
function showSuccess(message) {
  downloadStatus.innerHTML = `<p class="success">${message}</p>`;
}

// 清理下载状态
function cleanupDownloadState() {
  isDownloading = false;
  cancelBtn.style.display = 'none';

  // 清理进度监听器
  if (downloadProgressHandler) {
    window.electronAPI.removeAllListeners('download-progress');
    downloadProgressHandler = null;
  }
}

// 处理取消下载
function handleCancelDownload() {
  if (!isDownloading) return;

  // 清理下载状态
  cleanupDownloadState();

  // 显示取消信息
  showError('下载已取消');

  // 重新启用下载按钮
  downloadBtn.disabled = false;
  downloadBtn.textContent = '开始下载';

  // 隐藏下载区域
  downloadSection.style.display = 'none';
}

// 处理下载
async function handleDownload() {
  const selectedOptions = {
    os: osSelect.value,
    arch: archSelect.value,
    version: versionSelect.value,
    vendor: vendorSelect.value
  };

  // 验证选择
  if (!selectedOptions.os || !selectedOptions.arch || !selectedOptions.version || !selectedOptions.vendor) {
    showError('请完整选择所有选项。');
    return;
  }

  try {
    // 设置下载状态
    isDownloading = true;

    // 禁用下载按钮
    downloadBtn.disabled = true;
    downloadBtn.textContent = '正在下载中...';

    // 显示取消按钮
    cancelBtn.style.display = 'block';

    // 显示下载区域
    downloadSection.style.display = 'block';
    resultSection.style.display = 'none';

    // 自动滚动到下载进度区域
    setTimeout(() => {
      downloadSection.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    }, 100);

    // 重置进度条
    progressFill.style.width = '0%';
    progressText.textContent = '0%';
    downloadDetails.textContent = '已下载: 0 MB / 总大小: 0 MB';
    downloadStatus.innerHTML = '<p>正在准备下载...</p>';

    // 设置进度监听器
    if (downloadProgressHandler) {
      window.electronAPI.removeAllListeners('download-progress');
    }
    downloadProgressHandler = (event, progressData) => updateDownloadProgress(progressData);
    window.electronAPI.onDownloadProgress(downloadProgressHandler);

    // 开始下载
    const result = await window.electronAPI.downloadJdk(selectedOptions);

    // 下载成功
    showSuccess('下载完成！');
    resultSection.style.display = 'block';
    resultPath.textContent = `文件保存路径: ${result.filePath}`;

    // 自动滚动到结果区域
    setTimeout(() => {
      resultSection.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    }, 100);

    // 清理下载状态
    cleanupDownloadState();

    // 重新启用下载按钮
    downloadBtn.disabled = false;
    downloadBtn.textContent = '开始下载';

  } catch (error) {
    console.error('下载失败:', error);
    showError(`下载失败: ${error.message}`);

    // 清理下载状态
    cleanupDownloadState();

    // 重新启用下载按钮
    downloadBtn.disabled = false;
    downloadBtn.textContent = '开始下载';
  }
}

// 事件监听器
vendorSelect.addEventListener('change', updateOSOptions);
osSelect.addEventListener('change', updateArchitectureOptions);
archSelect.addEventListener('change', updateVersionOptions);
downloadBtn.addEventListener('click', handleDownload);
cancelBtn.addEventListener('click', handleCancelDownload);

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initApp);
